package com.dd.ljzapplication.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.dd.ljzapplication.R;
import com.dd.ljzapplication.adapter.HXPictureAdapter;
import com.dd.ljzapplication.adapter.HXPictureAdapter1;
import com.dd.ljzapplication.adapter.HXVideoAdapter;
import com.dd.ljzapplication.view.GridLayoutManagerInScrollView;
import com.emiage.ddutils.ActivityUtils;
import com.emiage.ddutils.FileUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import base.BaseUtilActivity;

/**
 * Created by LiJZ on 2016/10/11.
 *
 * 魅族手机存在bug，调用系统录像会直接finish掉，但是没有报错，try catch也拦截不到，其他手机没事
 * 
 */
public class HXBankActivity extends BaseUtilActivity implements View.OnClickListener {
	//水印文字宽度
	private int WATER_TEXT_WIDTH = 600;
	//图片上水印文字大小
	private int WATER_MARK_TEXT_SIZE = 18;
	//水印文字距图片底部距离
	private int WATER_MARK_TEXT_ABOVE_BOTTOM = 75;

	private Button mBtnCamera;
	private Button mBtnVideo;
	private Button mBtnAdd;
	private String path;
	private RecyclerView mRecyclerView;
	private HXPictureAdapter mAdapter;
	private HXVideoAdapter mVideoAdapter;
	private HXPictureAdapter1 mAdapter1;
	private ArrayList<String> mListPath = new ArrayList<>();
	private ArrayList<String> mVideoListPath = new ArrayList<>();
	private ImageView mImageView;

	private ArrayList<Bitmap> listData = new ArrayList<>();

	private boolean isCamear = true;
//	private VideoView mVideoView;
	private RecyclerView mVideoList;


//	private String picture = "/storage/emulated/0/.aaaa/CAMERA/IMG_1476802756053.JPEG";

	@Override
	protected int setLayoutID() {
		return R.layout.activity_hxback;
	}

	@Override
	protected void init() {

	}

	@Override
	protected void initActionBar() {

	}

	@Override
	protected void initView() {
		//把拍照和摄像分开，无法再一个页面又是点击标题又是拍照和摄像，手机屏幕太小。如果非要这样需要重写拍照和摄像的界面
		/*
		在某个采集项中点击，默认进行拍照采集。点击某个采集项的标题，可以切换为摄像采集。如需返回拍照采集，可再次点击采集项的标题，此时采集变为拍照采集。
		采集的照片中记录了客户经理名称、拍照或摄像所在的位置以及拍照或摄像时间，这些信息自动生成并形成水印保存在照片里，不可修改。
		视频无法生成水印，只记录视频即可。
		长按采集到的照片或摄像，可将其删除。
		 */
		mBtnCamera = (Button) findViewById(R.id.btn1);
		mBtnVideo = (Button) findViewById(R.id.btn2);
		mBtnAdd = (Button) findViewById(R.id.btn3);
		mRecyclerView = (RecyclerView) findViewById(R.id.rv);
		mImageView = (ImageView) findViewById(R.id.iv);
		mVideoList = (RecyclerView) findViewById(R.id.rv_video);
//		mImageView.setImageBitmap(BitmapFactory.decodeFile(picture));

		GridLayoutManager layoutManager = new GridLayoutManager(this, 3);
		GridLayoutManagerInScrollView layoutManagerInScrollView = new GridLayoutManagerInScrollView(this, 3);
		mRecyclerView.setLayoutManager(layoutManagerInScrollView);
		mAdapter = new HXPictureAdapter(this);
		mAdapter1 = new HXPictureAdapter1(this);
		mRecyclerView.setAdapter(mAdapter);
		mAdapter.setDate(mListPath);
		mAdapter1.setDate(listData);
		GridLayoutManagerInScrollView layoutManagerInScrollView1 = new GridLayoutManagerInScrollView(this, 3);
		mVideoList.setLayoutManager(layoutManagerInScrollView1);
		mVideoAdapter = new HXVideoAdapter(this);
		mVideoList.setAdapter(mVideoAdapter);
		mVideoAdapter.setDate(mVideoListPath);
	}

	@Override
	protected void initEvent() {
		mBtnCamera.setOnClickListener(this);
		mBtnVideo.setOnClickListener(this);
		mBtnAdd.setOnClickListener(this);
		mAdapter.setOnRVItemClickListener(new HXPictureAdapter.OnRVItemClickListener() {
			@Override
			public void setItemClickListener(View v, int position) {
				Log.i("####", "setItemClickListener: " + mListPath.get(position));
				ActivityUtils.startActivityForStringData(HXBankActivity.this, ShowBigPictureActivity.class, "path", mListPath.get(position));
			}
		});

		mAdapter.setOnRVItemLongClickListener(new HXPictureAdapter.OnRVItemLongClickListener() {
			@Override
			public void setItemLongClickListener(View v, int position) {
				Log.i("####", "LongClick: " + mListPath.get(position));
				mListPath.remove(position);
				mAdapter.notifyDataSetChanged();
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.btn1:
				Intent intent = new Intent();
				isCamear = true;
				intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
				this.path = Environment.getExternalStorageDirectory().getPath() + "/.aaaa/CAMERA/" + "IMG_" + System.currentTimeMillis() + ".JPEG";
				File file = FileUtils.createFile(this.path);
				Uri uri = Uri.fromFile(file);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
				if (intent.resolveActivity(getPackageManager()) != null) {
					startActivityForResult(intent, 0);
				}
				break;
			case R.id.btn2:
				isCamear = false;
				Intent intent1 = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
				intent1.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
//				intent1.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
//				intent1.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 300);//限制录制时间10秒
//				this.path = Environment.getExternalStorageDirectory().getPath() + "/.aaaa/CAMERA/" + "VEDIO" + System.currentTimeMillis() + ".MP4";
//				File file1 = FileUtils.createFile(this.path);
//				Uri uri1 = Uri.fromFile(file1);
//				intent1.putExtra(MediaStore.EXTRA_OUTPUT, uri1);
//
//				intent1.putExtra(MediaStore.EXTRA_FINISH_ON_COMPLETION,true);
				if (intent1.resolveActivity(getPackageManager()) != null) {
					try {
						startActivityForResult(intent1, 123);
					} catch (Exception e) {
						Toast.makeText(this, "Your device does not contain an application to run this action", Toast.LENGTH_LONG).show();
						e.printStackTrace();
					}
				} else {
					Toast.makeText(this, "111111111111111111111111", Toast.LENGTH_LONG).show();
				}
				break;
			case R.id.btn3:
//				mListPath.add(0, picture);
//				mAdapter.notifyItemInserted(0);
//				mRecyclerView.scrollToPosition(0);
//				mListPath.add(picture);
//				mAdapter.notifyDataSetChanged();
				return;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			if (requestCode==123) {
				Toast.makeText(this,"123",Toast.LENGTH_SHORT).show();
			}
			if (isCamear) {//拍照
				mRecyclerView.setVisibility(View.VISIBLE);
				Bitmap bitmap = getBitmap();
				mListPath.add(0, path);
				mAdapter.notifyItemInserted(0);
				mRecyclerView.scrollToPosition(0);
				/*mListPath.add(path);
				mAdapter.notifyDataSetChanged();
				Log.i("####", "onActivityResult: " + path);
				Log.i("####", "onActivityResult: " + mListPath.toString());
				*/

//				Bundle extras = data.getExtras();
//				Bitmap imageBitmap = (Bitmap) extras.get("data");
//				mImageView.setImageBitmap(imageBitmap);
//				listData.add(imageBitmap);
//				mAdapter1.notifyDataSetChanged();

				ByteArrayOutputStream bStream = new ByteArrayOutputStream();
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bStream);
				byte[] bytes = bStream.toByteArray();
				Log.i("####", "Bitmap: " + bitmap.getByteCount());
				Log.i("####", "bytes: " + bytes.length);
			} else {//录像
//				Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath()+"/Test_Movie.m4v");
//				videoView.setMediaController(new MediaController(this));
//				videoView.setVideoURI(uri);
//				videoView.start();
//				videoView.requestFocus();
				/*mRecyclerView.setVisibility(View.GONE);
				mVideoView.setVisibility(View.VISIBLE);

				mVideoView.setVideoPath(path);
				mVideoView.setMediaController(new MediaController(this));
				mVideoView.requestFocs();
				mVideoView.start();*/

				mVideoListPath.add(path);
				mVideoAdapter.notifyDataSetChanged();
			}
		}
	}

	private Bitmap getBitmap() {
		final Bitmap bitmap = BitmapFactory.decodeFile(path);
		final Bitmap bitmap1 = addWaterMark(bitmap, "客户经理001，北京xxx有限公司");
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					// TODO: 2016/10/18  createFile(path) 可以直接使用上面创建的file，因为还有录像没有考虑，以后再说
					FileOutputStream fos = new FileOutputStream(FileUtils.createFile(path));
					bitmap1.compress(Bitmap.CompressFormat.JPEG, 100, fos);
					fos.flush();
					fos.close();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();
		return bitmap1;
	}

	public Bitmap addWaterMark(Bitmap src, String water) {
		Bitmap tarBitmap = src.copy(Bitmap.Config.ARGB_8888, true);
		int w = tarBitmap.getWidth();
		int h = tarBitmap.getHeight();
		Canvas canvas = new Canvas(tarBitmap);
		//启用抗锯齿和使用设备的文本字距
		TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
		//字体的相关设置
		textPaint.setTextSize(50);//字体大小
		textPaint.setTypeface(Typeface.DEFAULT_BOLD);
		textPaint.setColor(Color.YELLOW);
		//图片上添加水印的位置
		float v = textPaint.measureText(water);
		canvas.drawText(water, (w - v) / 2, (float) (h - 150), textPaint);
		canvas.save(Canvas.ALL_SAVE_FLAG);
		canvas.restore();
		return tarBitmap;
	}

	/**
	 * 添加水印.文字过长可以自动换行
	 *
	 * @param src
	 * @param water
	 * @return
	 */
	public Bitmap addWaterMark1(Bitmap src, String water) {
		Bitmap tarBitmap = src.copy(Bitmap.Config.ARGB_8888, true);
		int w = tarBitmap.getWidth();
		int h = tarBitmap.getHeight();
		Canvas canvas = new Canvas(tarBitmap);
		//启用抗锯齿和使用设备的文本字距
		TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
		//字体的相关设置
		textPaint.setTextSize(WATER_MARK_TEXT_SIZE);//字体大小
		textPaint.setTypeface(Typeface.DEFAULT_BOLD);
		textPaint.setColor(Color.WHITE);
		//设置文字换行
		StaticLayout layout = new StaticLayout(water, textPaint, WATER_TEXT_WIDTH, Layout.Alignment.ALIGN_NORMAL, 1.0F, 0.0F, true);
		canvas.save();
		float v = textPaint.measureText(water);
		if (v > WATER_MARK_TEXT_SIZE) {
			canvas.translate((float) ((w - WATER_MARK_TEXT_SIZE) / 2), (float) (h - WATER_MARK_TEXT_ABOVE_BOTTOM));//开始画的位置
		} else {
			canvas.translate((w - v) / 2, (float) (h - WATER_MARK_TEXT_ABOVE_BOTTOM));
		}
		layout.draw(canvas);
		canvas.restore();
		return tarBitmap;
	}
}
